<template>
<!-- 面包屑导航区域-->
<el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item>首页</el-breadcrumb-item>
    <el-breadcrumb-item>课程管理</el-breadcrumb-item>
</el-breadcrumb>

<!--以下是主页面列表-->
<el-card class="card">
  <div class="button_div">
    <el-button type="success" @click="addCourse()" :disabled="b_s" >新增</el-button>
    <el-button type="warning" @click="updateCourse" :disabled="b_s" >修改</el-button>
    <el-button type="danger" @click="deleteCourse" :disabled="b_s" >删除</el-button>
    <span class="span_t">[点击对应条目实现单选]--已选中:</span>
    <span class="span_s">{{ select }}</span>
  </div>
    <el-table highlight-current-row @current-change="handleCurrentChange" :data="paginatedData" style="width: 100%">
      <el-table-column type="index" label="序号" width="55" >
        <!--                    以下是确保在第二页的时候。序号从11开始-->
        <template v-slot="scope">
                        <span>
                            {{ (this.currentPage- 1) * this.pageSize + scope.$index + 1 }}
                        </span>
        </template>
      </el-table-column>
            <el-table-column prop="course_code" label="课程代码" width="180" />
            <el-table-column prop="course_name" label="课程名称" width="180" />
            <el-table-column prop="course_number" label="课程人数" width="180" />

        </el-table>
  <!-- 分页栏 -->
  <div class="pagination">
    <el-pagination
        background
        layout="prev, pager, next"
        :total="tableData.length"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handleCurrentChange"/>
  </div>
</el-card>
  <!--新增的对话框-->
  <el-dialog v-model="Addvisual" title="添加课程信息" width="50%">
    <AddCourse @close-dialog="closeAddForm()" @submit-form="submitAddForm" />
  </el-dialog>
  <el-dialog v-model="Upvisual" title="修改课程信息" width="50%">
    <UpCourse :current-course="currentRow" @close-dialog="closeUpForm()" @submit-form="submitUpForm" />
  </el-dialog>
</template>

<script>
import CourseApi from "@/api/CourseApi";
import AddCourse from "@/components/FormWin/AddForm/AddCourse.vue";
import UpCourse from "@/components/FormWin/UpdataForm/UpCourse.vue";
import stroe from "../store/index"

export default{
  components: {UpCourse, AddCourse},
  data(){
    return{
      tableData:[],
      select:"未选中",
      currentRow: null,
      pageSize: 10, // 默认每页显示的条数
      currentPage: 1, // 当前页码
      Addvisual:false,//新增表单的显示
      Upvisual:false//修改表单的
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
    b_s(){ //如果是管理员，按钮可选
      if(stroe.state.userType=='admin'){
        return false;
      }
      return true;
    }
  },
  methods:{
    Frensh(){
      CourseApi.getAll().then(res => {
        this.tableData = res.data.tableData;
      });
    },
    handleCurrentChange(val) {
      this.currentRow = val;
      if (val) {
        this.select = `第${this.paginatedData.findIndex(row => row.course_name === val.course_name) + 1}条 - 课程名称: ${val.course_name}}`;
      }
      else {
        this.select = "未选中";
      }
    },
    addCourse() {
      // 新增课程逻辑
      this.Addvisual=true;
      //显示表单后，后面去表单提交函数执行
    },
    updateCourse() {
      if (!this.currentRow) {
        this.$message({
          message: '请先选择要修改的课程',
          type: 'warning'
        });
        return;
      }
      // 修改课程逻辑
      this.Upvisual=true;
    },
    deleteCourse() {
      // 删除课程逻辑
      if (!this.currentRow) {
        this.$message({
          message: '请先选择要删除的课程',
          type: 'warning'
        });
        return;
      }
      //已经选中了后
      else{
        this.$confirm(`确定要删除课程 ${this.currentRow.name} (课程名: ${this.currentRow.course_name}) 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {// 用户确认删除
          CourseApi.del_one(this.currentRow.course_name).then(res => {
            if (res.data === 1) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }
            else{
              this.$message({
                message: '[删除失败]-此课程已有学生在读！',
                type: 'error'
              });
            }
            this.Frensh();
          })
        }).catch(()=>{
          this.$message({
            message: '取消删除',
            type: 'success'
          });
        })
      }
    },
    //以下是弹出表单相关的处理方法。
    //打开，关闭。
    closeAddForm(){
      this.Addvisual=false;
    },
    closeUpForm(){
      this.Upvisual=false;
    },
    //以下是表单提交等
    submitAddForm(formDate){
      //先要验证，课程是否重复了
      const idExists = this.tableData.some(course => course.course_name === formDate.course_name);
      if (idExists) {
        this.$message({
          message: '课程已存在！',
          type: 'warning'
        });
        this.Addvisual=false;
        return;
      } else {
        //如果课程没重复，合法的，存后端。
        CourseApi.add_one(formDate).then(res=>{
          if(res.data==1){
            this.$message({
              message:'添加课程成功！',
              type:'success'
            })
            this.Addvisual=false;
            //如果成功，刷新页面
            this.Frensh();
          }
          else{
            this.$message({
              message:'添加课程失败！',
              type:'error'
            })
            this.Addvisual=false;
          }
        })

      }
    },
    //修改
    submitUpForm(formDate){
      this.$confirm(`确定要修改课程: ${this.currentRow.course_name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {// 用户确认修改
        CourseApi.updata_one(formDate,this.currentRow.course_name).then(res => {
          if (res.data === 1) {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
          }
          this.Upvisual=false;
          this.Frensh();
        })
      }).catch(()=>{
        this.$message({
          message: '取消修改',
          type: 'success'
        });
      })
    },
    handleResize() {
      // 检查窗口高度并调整pageSize
      const  win_height=window.innerHeight;
      if(win_height <= 750){
        this.pageSize = 10;
      }
      else if (win_height > 750 && win_height <=800) {
        this.pageSize = 11;
      }
      else if(win_height > 800 &&  win_height<=850){
        this.pageSize = 12;
      }
      else if(win_height > 850 && win_height <=900){
        this.pageSize = 13;
      }
      else if(win_height > 900 && win_height <=950){
        this.pageSize = 14;
      }
      else if(win_height > 950) {
        this.pageSize = 15;
      }
    }
  },
  created(){
    //刷新界面就重新获取一遍
    CourseApi.getAll().then(res=>{
      this.tableData=res.data.tableData;
    })
  },
  mounted() {
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }
}
</script>
<style lang="css" src="../styles/main.css" scoped />
